import React, { Component } from 'react';
import QueueAnim from 'rc-queue-anim';
import { toJS } from 'mobx';
import { observer, inject } from 'mobx-react';
import { withRouter, Route, Link } from 'react-router-dom';
import { Icon, SearchBar, Tools, Popover, Button, Bubble } from 'weaver-mobile';
import { ListViewPage, SearchPage, SearchAdvanced } from 'weaver-mobile-page';

import { attachmentCondition } from '../../apis/attachment';
import { compareParams } from '../../util';

import New from '../new/New';
import View from '../view/View';
import NavBar from '../widget/NavBar';
import FilePreview from './filePreview';

const { Item } = Popover;
const { getLabel, getWeaverFile } = Tools;

@inject('attachmentStore')
@withRouter
@observer
export default class Attachment extends Component {
  static defaultProps = {
    prefixCls: "email-attachment",
  };

  constructor(props) {
    super(props)
  
    this.state = {
      defaultParams: {}
    }
  }
  

  componentDidMount() {
    const { attachmentStore } = this.props;
    const { listViewStore, template, searchAdvancedStore, configUrl } = attachmentStore;
    attachmentStore.clear();
    listViewStore.selectNone();
    listViewStore.setState({ template });
    configUrl();
 
    searchAdvancedStore.getData({ url: attachmentCondition }).then(form => {
      this.setState({defaultParams: form.formParams})
      listViewStore.clearData();
      attachmentStore.getData({ ...form.formParams });
    //  this.onSearchAdvancedReset();
    //  this.onSearch()
    });
 
  }

  getTemplate = () => {
    const { prefixCls } = this.props;
    const newTemp = {
      default: [{
        key: 'col_1',
        render: (data) => {
          const { filenamespan, filesizespan, senddatespan } = data;
          return (
            <div onClick={() => this.onRowClick(data)} className={`${prefixCls}-list-template`}>
              <div className={`${prefixCls}-title`}>{filenamespan}</div>
              <div className={`${prefixCls}-info`}><span>{filesizespan}</span> <span>{senddatespan}</span></div>
            </div>
          );
        },
      }],
    };
    return newTemp;
  }

  onRowClick = (data) => {
    const { attachmentStore, history } = this.props;
    const { showCheck, routes: { filePreview } } = attachmentStore;
    if (showCheck) { return; }
    attachmentStore.setState({ file: data });
    history.push(filePreview);
  }

  onWriteNew = () => {
    const { attachmentStore, history } = this.props;
    const { listViewStore, listViewStore: { selectedRowKeys }, routes: { writeNew }, sysConfig } = attachmentStore;
    let attachCount = sysConfig.attachmentCount;
    if (selectedRowKeys.length > attachCount) {
      Bubble.error(`${getLabel(388819, '已选附件个数已超过邮件后台附件设置的附件总数')+  attachCount+","+getLabel(513069, '请重新选择或设置')}`, 1, { top: '50%' });
      return ;
    }
    attachmentStore.setState({ newParams: { fileid: [...selectedRowKeys], title: getLabel('30912','写信') }, showCheck: false });
    listViewStore.selectNone();
    history.push(writeNew);
  }

  getSwipeActionProps = () => {
      const { attachmentStore } = this.props;
      const { prohibitDownload } = attachmentStore;
    return   prohibitDownload=="0"?({
      right: [
        {
          text: getLabel('30912','写信'),
          onPress: (data) => {
            const { attachmentStore, history } = this.props;
            const { routes: { writeNew } } = attachmentStore;
            attachmentStore.setState({ newParams: { fileid: [data.id], title: getLabel('30912','写信') }});
            history.push(writeNew);
          },
          className: `${this.props.prefixCls}-write`,
        },
        {
          text: getLabel('31156', '下载'),
          onPress: (data) => {
            if(Tools.mobileDetect().is('iPhone')&&!Tools.mobileDetect().isEmobile()) {
              window.open(data.downloadUrlspan+"&_ec_ismobile=true");
              // let url = data.downloadUrlspan;
              // var fileId = '';
              // fileId = url.slice(url.indexOf('fileid='));
              // fileId = fileId.slice(0, fileId.indexOf('&'));
              // Tools.callApi({
              //     url: '/api/doc/mobile/imagefile/getMobileDownloadParams?' + fileId,
              //     method: 'GET',
              //     params: {
              //         type: 'email'
              //     },
              //     type: 'json'
              // }).then(function (res) {
              //     if (res.params) {
              //         url += res.params;
              //     }

              //     window.location = url+"&_ec_ismobile=true";
              // })['catch'](function () {
              //     // console && console.log('get download info failed ' + JSON.stringify(error))
              //   window.location = data.downloadUrlspan + "&_ec_ismobile=true";
              // });
            } else {
              getWeaverFile(data.downloadUrlspan+`&_ec_ismobile=true`, 'iframe','email');
            }
          },
          className: `${this.props.prefixCls}-download`,
        },
        {
          text: getLabel('500259', '查看相关邮件'),
          onPress: (data) => {
            const { attachmentStore, history } = this.props;
            const { routes: { mailView } } = attachmentStore;
            attachmentStore.setState({ mailid: data.mailid });
            history.push(`${mailView}/${data.mailid}`);
          },
          className: `${this.props.prefixCls}-check-email`,
        },
      ],
    }):
    ({
      right: [
        {
          text: getLabel('30912','写信'),
          onPress: (data) => {
            const { attachmentStore, history } = this.props;
            const { routes: { writeNew } } = attachmentStore;
            attachmentStore.setState({ newParams: { fileid: [data.id], title: getLabel('30912','写信') }});
            history.push(writeNew);
          },
          className: `${this.props.prefixCls}-write`,
        },
        {
          text: getLabel('500259', '查看相关邮件'),
          onPress: (data) => {
            const { attachmentStore, history } = this.props;
            const { routes: { mailView } } = attachmentStore;
            attachmentStore.setState({ mailid: data.mailid });
            history.push(`${mailView}/${data.mailid}`);
          },
          className: `${this.props.prefixCls}-check-email`,
        },
      ],
    })
  }

  onSearch = () => {
    const { attachmentStore } = this.props;
    const { searchParams,
      searchAdvancedStore: { form: { formParams } },
      listViewStore,
      searchKey,
      localeStorageKey,
    } = attachmentStore;
    listViewStore.clearData();
    attachmentStore.getData({ ...formParams, ...searchParams });
    const currentValue = formParams[searchKey] || '';
    if (currentValue) {
      let searchHistory = localStorage.getItem(localeStorageKey);
      searchHistory = searchHistory ? JSON.parse(searchHistory) : [];
      searchHistory = searchHistory.filter(h => h.key !== currentValue);
      searchHistory.unshift({ key: currentValue, name: currentValue });
      localStorage.setItem(localeStorageKey, JSON.stringify(searchHistory));
    }
  }

  onSearchAdvancedReset = () => {
    const { attachmentStore,  } = this.props;
    const { searchParams, searchKey } = attachmentStore;
    attachmentStore.setState({ searchParams: { ...searchParams, [searchKey]: '' } });
  }

  onSearchAdvancedChange = (c, value) => {
    const { attachmentStore } = this.props;
    const { searchParams, searchKey } = attachmentStore;
    if (c.domkey[0] === searchKey) {
      attachmentStore.setState({ searchParams: { ...searchParams, [searchKey]: value } });
    }
  }

  onSearchPageClear = () => {
    const { attachmentStore } = this.props;
    const { searchPageStore, localeStorageKey } = attachmentStore;
    localStorage.removeItem(localeStorageKey);
    searchPageStore.list.setState({ data: [] });
  }

  onSearchPageChange = (v) => {
    const { attachmentStore } = this.props;
    const { searchAdvancedStore, searchKey } = attachmentStore;
    attachmentStore.setState({ searchParams: { [searchKey]: v } });
    if (searchAdvancedStore && searchAdvancedStore.form) {
      searchAdvancedStore.form.updateField(searchKey, v);
    }
  }

  render() {
    const { attachmentStore, history, prefixCls } = this.props;
    const {
      file,
      showCheck,
      showPopover,
      listViewStore,
      listViewStore: { selectedRowKeys, isSelectedAll },
      searchAdvancedStore,
      searchAdvancedStore: { form },
      searchPageStore,
      searchParams,
      searchKey,
      mailid,
      routes: { searchPage, writeNew, mailView, filePreview, searchAd },
      newParams,
      localeStorageKey,
      updateListData,
    } = attachmentStore;

    const compare = compareParams(toJS(form.formParams), toJS(this.state.defaultParams));
    const searchAdIcon = (form && !compare) ?
      (<Icon className={`${prefixCls}-search-advanced-unempty`} type="filter-o-hot" />) :
      (<Icon type="filter-o" />);
    return (
      <QueueAnim>
        <div className={`${prefixCls} wm-route-layout`} key="email-attachment">
          <SearchAdvanced
            store={searchAdvancedStore}
            onSubmit={this.onSearch}
            onReset={this.onSearchAdvancedReset}
            onChange={this.onSearchAdvancedChange}
          />
          <SearchPage
            searchValue={searchParams[searchKey] || ''}
            store={searchPageStore}
            rowKey="key"
            nameKey="name"
            type={1}
            onChange={this.onSearchPageChange}
            onSubmit={(v) => {
              this.onSearchPageChange(v);
              this.onSearch();
            }}
            onClear={this.onSearchPageClear}
          />
          <SearchBar
            className="search-select"
            placeholder={getLabel('500351', '请输入关键字')}
            value={searchParams[searchKey] || ''}
            showExtraButton
            extraButton={[
              { key: 'searchAd', show: <Link to={searchAd}>{searchAdIcon}</Link> },
              { key: 'popover', show:
              <Popover
                mask
                visible={showPopover}
                overlay={[<Item>{getLabel('500410', '批量操作')}</Item>]}
                onVisibleChange={v => attachmentStore.setState({ showPopover: v })}
                onSelect={() => attachmentStore.setState({ showPopover: false, showCheck: true })}
              >
                <Icon type="ellipsis" />
              </Popover>
              },
            ]}
            onFocus={() => {
              history.push(searchPage);
              let searchHistory = localStorage.getItem(localeStorageKey);
              searchHistory = searchHistory ? JSON.parse(searchHistory) : [];
              searchPageStore.list.setState({ data: searchHistory });
            }}
          />
          {showCheck ? (<div className={`${prefixCls}-all am-list-item`}>
                <span className={`${prefixCls}-all-choise`}>
                  <span
                    className={`${prefixCls}-all-cancel`}
                    onClick={() => {attachmentStore.setState({ showCheck: false }); listViewStore.selectNone();}}
                  >{getLabel('31129', '取消')}</span>
                  <span>{`${getLabel('31503', '已选择')}${selectedRowKeys.length}${getLabel('83077', '个附件')}`}</span>
                </span>
                <span
                  className={`${prefixCls}-all-select`}
                  onClick={() => (isSelectedAll ? listViewStore.selectNone() : listViewStore.selectAll())}
                >
                  {`${isSelectedAll ? getLabel('31129', '取消') : ''}${getLabel('556', '全选')}`}
                </span>
              </div>) : null}
          <div className={`${prefixCls}-list-view`}>
            <ListViewPage.Normal
              className={`${prefixCls}-list ${showCheck ? 'showCheck' : ''}`}
              showCheck={showCheck}
              store={listViewStore}
              withSwipeAction
              customHeight="100%"
              swipeActionProps={this.getSwipeActionProps()}
              getTemplate={this.getTemplate}
            />
          </div>
          {showCheck ?
            (<div className={`${prefixCls}-btn-group`}>
              <Button disabled={!selectedRowKeys.length} type="primary" onClick={this.onWriteNew}>{getLabel('30912','写信')}</Button>
            </div>) : <NavBar path={writeNew} />}
          <Route
            key="filePreview"
            path={filePreview}
            render={() => (<FilePreview path={filePreview} file={file} />)}
          />
          <Route
            key="view"
            path={`${mailView}/:id`}
            render={() => (<View path={`${mailView}/${mailid}`} refreshList={this.onSearch} updateListData={updateListData} from='attachment'/>)}
          />
          <Route
            key="new"
            path={writeNew}
            render={() => (<New path={writeNew} params={newParams}/>)}
          />
        </div>
      </QueueAnim>
    );
  }
}